import os
import subprocess
import time
import xml.etree.ElementTree as ET
import re
import logging

# 配置logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def open_mihome_app():
    """使用ADB命令打开米家APP"""
    try:
        # 检查设备连接
        logger.debug("正在检查ADB设备连接...")
        check_device = subprocess.run(['adb', 'devices'], 
                                   capture_output=True, 
                                   text=True)
        if 'device' not in check_device.stdout:
            raise Exception("没有找到已连接的设备")
        logger.info("ADB设备连接正常")

        # 启动米家APP
        logger.debug("正在启动米家APP...")
        launch_command = [
            'adb', 
            'shell', 
            'am', 
            'start', 
            '-n', 
            'com.xiaomi.smarthome/com.xiaomi.smarthome.SmartHomeMainActivity'
        ]
        
        result = subprocess.run(launch_command, 
                              capture_output=True, 
                              text=True)
        
        if result.returncode == 0:
            logger.info("米家APP启动成功")
            logger.debug("等待APP完全启动(3秒)...")
            time.sleep(3)
            find_and_click_lock()
        else:
            logger.error(f"启动失败: {result.stderr}")
            
    except Exception as e:
        logger.error(f"启动APP时发生错误: {str(e)}")

def get_ui_xml():
    """获取当前界面的XML布局"""
    try:
        logger.debug("正在获取界面布局...")
        subprocess.run(['adb', 'shell', 'uiautomator', 'dump', '/sdcard/window_dump.xml'])
        subprocess.run(['adb', 'pull', '/sdcard/window_dump.xml', '.'])
        tree = ET.parse('window_dump.xml')
        return tree.getroot()
    except Exception as e:
        logger.error(f"获取界面布局失败: {str(e)}")
        return None

def find_and_click_lock():
    """查找并点击门锁控件"""
    try:
        root = get_ui_xml()
        if root is None:
            return

        logger.debug("正在查找门锁控件...")
        lock_node = None
        for node in root.findall(".//node"):
            if "门锁" in node.attrib.get('text', ''):
                lock_node = node
                break
                
        if lock_node is not None:
            bounds = lock_node.attrib['bounds']
            coordinates = re.findall(r'\d+', bounds)
            x = (int(coordinates[0]) + int(coordinates[2])) // 2
            y = (int(coordinates[1]) + int(coordinates[3])) // 2
            
            logger.info(f"找到门锁控件，坐标: ({x}, {y})")
            logger.debug("正在点击门锁控件...")
            
            subprocess.run(['adb', 'shell', 'input', 'tap', str(x), str(y)])
            logger.info("已点击门锁控件")
            
            # 等待连接
            wait_for_lock_connection()
        else:
            logger.warning("未找到门锁控件")
            
        # 清理临时文件
        cleanup_files()
        
    except Exception as e:
        logger.error(f"查找门锁时发生错误: {str(e)}")

def wait_for_lock_connection():
    """等待门锁连接成功"""
    logger.info("等待门锁连接...")
    max_attempts = 20  # 最多等待20次
    attempt = 0
    
    while attempt < max_attempts:
        attempt += 1
        logger.debug(f"第{attempt}次检查连接状态...")
        
        root = get_ui_xml()
        if root is None:
            continue
            
        # 检查是否存在"未连接"或"连接中"的提示
        disconnected = False
        for node in root.findall(".//node"):
            text = node.attrib.get('text', '')
            if "未连接" in text or "连接中" in text:
                disconnected = True
                break
        
        if not disconnected:
            logger.info("门锁连接成功！")
            # 执行解锁操作
            unlock_door()
            return
            
        time.sleep(1)  # 等待1秒后重试
    
    logger.error("门锁连接超时")

def unlock_door():
    """执行解锁操作"""
    try:
        logger.info("开始执行解锁操作...")
        
        # 获取屏幕尺寸
        screen_size = subprocess.run(
            ['adb', 'shell', 'wm', 'size'], 
            capture_output=True, 
            text=True
        )
        size_match = re.search(r'(\d+)x(\d+)', screen_size.stdout)
        if not size_match:
            logger.error("无法获取屏幕尺寸")
            return
            
        screen_width = int(size_match.group(1))
        screen_height = int(size_match.group(2))
        
        # 计算解锁按钮的大致位置
        # 假设解锁按钮在屏幕中间偏上的位置
        x = screen_width // 2
        y = int(screen_height * 0.35)  # 屏幕35%的位置
        
        logger.info(f"屏幕尺寸: {screen_width}x{screen_height}")
        logger.info(f"计算的解锁按钮位置: ({x}, {y})")
        logger.debug("执行长按操作(2秒)...")
        
        # 执行长按操作（2秒）
        subprocess.run([
            'adb', 
            'shell', 
            'input', 
            'swipe', 
            str(x), str(y), 
            str(x), str(y), 
            '2000'
        ])
        
        logger.info("解锁操作完成")
            
    except Exception as e:
        logger.error(f"解锁操作失败: {str(e)}")

def cleanup_files():
    """清理临时文件"""
    try:
        logger.debug("清理临时文件...")
        if os.path.exists('window_dump.xml'):
            os.remove('window_dump.xml')
        subprocess.run(['adb', 'shell', 'rm', '/sdcard/window_dump.xml'])
    except Exception as e:
        logger.error(f"清理文件时发生错误: {str(e)}")

if __name__ == "__main__":
    open_mihome_app()
